package com.zsr.example.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import com.zsr.example.config.WXPayConfigProperties;
import com.zsr.example.config.exception.CommonJsonException;
import com.zsr.example.entity.*;
import com.zsr.example.mapper.TPayLogMapper;
import com.zsr.example.service.*;
import com.zsr.example.util.HttpClient;
import com.zsr.example.util.constants.BusinessEnum;
import com.zsr.example.util.constants.ErrorEnum;
import com.zsr.example.util.constants.OrderConstants;
import org.apache.poi.ss.formula.functions.T;
import org.aspectj.weaver.Lint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author zsr
 * @since 2021-12-06
 */
@Service
public class TPayLogServiceImpl extends ServiceImpl<TPayLogMapper, TPayLog> implements TPayLogService {
    @Autowired
    private TOrderService orderService;
    @Autowired
    private EduPathStepService pathStepService;
    @Autowired
    private EduPathStepRelationService pathStepRelationService;
    @Autowired
    private TOrderItemService orderItemService;
    //支付成功后要跳转的页面
    @Value("${alipay.returnUrl}")
    private String returnUrl;

    /**
     * 根据订单号生成wx二维码
     *
     * @param orderNo 订单号
     * @return
     */
    @Override
    public Map<String, Object> createNative(String orderNo) {
        try {
            //根据订单id获取订单信息
            QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no", orderNo);
            TOrder order = orderService.getOne(wrapper);

            Map<String, String> m = new HashMap();
            //1、设置支付参数
            m.put("appid", WXPayConfigProperties.PAY_APPID);//关联的公众号appid
            m.put("mch_id", WXPayConfigProperties.PAY_PARTNER);//商户号
            m.put("nonce_str", WXPayUtil.generateNonceStr());//sdk 生成随机字符串 生成二维码最终不一样
            m.put("body", order.getCourseTitle());//订单中的商品名
            m.put("out_trade_no", orderNo);
            m.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue() + "");//价格转为字符串
            m.put("spbill_create_ip", "127.0.0.1");//终端IP 或域名
            m.put("notify_url", WXPayConfigProperties.PAY_NOTIFYURL);
            m.put("trade_type", "NATIVE");//交易类型

            //开发文档 https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1
            //2、HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");

            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m, WXPayConfigProperties.PAY_PARTNERKEY));//商户key 加密参数转为xml
            client.setHttps(true);
            client.post();//发送请求
            //3、返回第三方的数据
            String xml = client.getContent();//xml格式
            //System.out.println(xml);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);//sdk xml转为map

            //4、封装返回结果集 (除了二维码 还需要其他信息)

            Map<String, Object> map = new HashMap<>();
            map.put("out_trade_no", orderNo);
            map.put("course_id", order.getTargetId());
            map.put("target_type", order.getTargetType());
            map.put("total_fee", order.getTotalFee());
            map.put("result_code", resultMap.get("result_code"));
            map.put("code_url", resultMap.get("code_url"));//wx支付的二维码

            //微信支付二维码2小时过期，可采取2小时未支付取消订单
            //redisTemplate.opsForValue().set(orderNo, map, 120, TimeUnit.MINUTES);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonJsonException(ErrorEnum.E_30002);
            //return new HashMap<>();
        }
    }

    /**
     * 更新订单状态
     *
     * @param map
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TOrder updateOrderStatus(Map<String, String> map) {
        //获取订单id
        String orderNo = map.get("out_trade_no");
        //根据订单id查询订单信息
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderNo);
        TOrder order = orderService.getOne(wrapper);
        if (order != null) {
            if (order.getStatus() == OrderConstants.STATUS_PAY) return order;
            //修改订单支付状态
            order.setStatus(OrderConstants.STATUS_PAY);
            if (map.get("pay_type").equals("2")) order.setPayType(OrderConstants.PAY_TYPE_ZFB);
            orderService.updateById(order);
            //如果是学习路径 特殊处理
            if (order.getTargetType() == BusinessEnum.PATH.getType()) {
                String pathId = order.getTargetId();
                List<EduPathStep> list = pathStepService.list(new LambdaQueryWrapper<EduPathStep>().eq(EduPathStep::getPathId, pathId));
                List<String> collect = list.stream().map(EduPathStep::getId).collect(Collectors.toList());
                List<EduPathStepRelation> courses = pathStepRelationService.list(new LambdaQueryWrapper<EduPathStepRelation>().in(EduPathStepRelation::getStepId, collect));
                if(!CollectionUtils.isEmpty(courses)){
                    List<TOrderItem> items=new ArrayList<>();
                    for (EduPathStepRelation cours : courses) {
                        items.add(new TOrderItem().setOrderNo(orderNo)
                                .setParentId(pathId)
                                .setParentName(order.getCourseTitle())
                                .setTargetType(cours.getTargetType())
                                .setTargetId(cours.getTargetId())
                                .setMemberId(order.getMemberId()));
                    }
                    orderItemService.saveBatch(items);
                }
            }

            //记录支付日志
            TPayLog payLog = new TPayLog();
            payLog.setOrderNo(order.getOrderNo());//支付订单号
            payLog.setPayTime(new Date());
            if (map.get("pay_type").equals("1")) {
                payLog.setPayType(OrderConstants.PAY_TYPE_WX);//支付类型
            } else {
                payLog.setPayType(OrderConstants.PAY_TYPE_ZFB);//支付类型
            }
            payLog.setTotalFee(order.getTotalFee());//总金额(分)
            payLog.setTradeState(map.get("trade_state"));//支付状态
            payLog.setTransactionId(map.get("transaction_id"));
            payLog.setAttr(JSONObject.toJSONString(map));
            baseMapper.insert(payLog);//插入到支付日志表
        }
        return order;
    }

    /**
     * 查询wx订单状态
     *
     * @param orderNo
     * @return
     */
    @Override
    public Map queryPayStatus(String orderNo) {
        try {
            //1、封装参数
            Map m = new HashMap<>();
            m.put("appid", WXPayConfigProperties.PAY_APPID);
            m.put("mch_id", WXPayConfigProperties.PAY_PARTNER);
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2、设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m, WXPayConfigProperties.PAY_PARTNERKEY));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            resultMap.put("pay_type", OrderConstants.PAY_TYPE_WX + "");
            //6、转成Map
            //7、返回
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成支付宝支付二维码
     *
     * @param orderNo
     * @return
     */
    @Override
    public Map<String, Object> createNativeByAlipay(String orderNo) {

        AlipayTradePrecreateResponse response;
        Map<String, Object> map = new HashMap<>();
        //根据订单id获取订单信息
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderNo);
        TOrder order = orderService.getOne(wrapper);
        try {
            response = Factory.Payment.FaceToFace()
                    //选择网页支付平台
                    //调用支付方法，设置订单名称、我们自己系统中的订单号、金额、回调页面3
                    .preCreate(order.getCourseTitle(), order.getOrderNo(), order.getTotalFee() + "");

            if (ResponseChecker.success(response)) {
                //System.out.println(response.getQrCode());
                map.put("code_url", response.getQrCode());
                map.put("course_id", order.getTargetId());
                map.put("target_type", order.getTargetType());
                map.put("out_trade_no", order.getOrderNo());
                map.put("result_code", "SUCCESS");
                map.put("total_fee", order.getTotalFee() + "");

            } else {

                System.out.println("调用失败，原因" + response.msg);
                System.out.println("调用失败，原因" + response.subMsg);
            }
            //这里的response.body，就是一个可以直接加载的html片段，
            // 这里为了简单我直接返回这个片段，前端直接
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonJsonException(ErrorEnum.E_30002);
        }
        return map;
    }

    /**
     * 查询支付宝订单状态
     *
     * @param orderNo
     * @return
     */
    @Override
    public Map<String, String> queryPayStatusByAlipay(String orderNo) {
        AlipayTradeQueryResponse query = null;
        Map<String, String> map = new HashMap<>();
        try {
            query = Factory.Payment.Common().query(orderNo);
            map.put("out_trade_no", orderNo);
            map.put("pay_type", OrderConstants.PAY_TYPE_ZFB + "");
            map.put("trade_state", query.getTradeStatus());
            map.put("transaction_id", query.getTradeNo());
            //未支付tradeStatus:WAIT_BUYER_PAY
            //已支付tradeStatus:TRADE_SUCCESS
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
